package com.asset.dispoal.file.document.service.command;

import com.asset.dispoal.file.common.FileCreateUtil;
import com.asset.dispoal.file.document.domain.db.entity.Document;
import com.asset.dispoal.file.document.domain.db.entity.DocumentParam;
import com.asset.dispoal.file.document.domain.db.mapper.DocumentMapper;
import com.asset.dispoal.file.document.dto.DocumentAddRequest;
import com.asset.dispoal.file.document.dto.DocumentParamAddRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

@Component
public class DocumentAddCommand implements BaseCommand<DocumentAddRequest, Result> {

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private Environment environment;

    @Override
    public Result execute(DocumentAddRequest request) {
        Document document = new Document();
        document.setId(idWorker.generateId());
        document.setDocumentTypeId(request.getDocumentTypeId());
        document.setName(request.getName());
        document.setSorted(request.getSorted());
        document.setAssetInstBatchId(request.getAssetInstBatchId());
        document.setCreateUserId(GlobalHeaderThreadLocal.getOrException().getUserId());
        document.setCreateTime(DateTimeUtil.currentDate());

        if (request.getFile() != null) {
            String headUrl = environment.getProperty("file.evidence.url");
            String appendUrl = environment.getProperty("file.document.url");
            String propertyUrl = FileCreateUtil.copyFile(document.getId(), request.getFile(), headUrl, appendUrl);
            document.setFileUrl(propertyUrl);
        }
        if (CollectionUtil.isNotEmpty(request.getParamList())) {
            for (DocumentParamAddRequest paramAddRequest : request.getParamList()) {
                DocumentParam param = new DocumentParam();
                param.setId(idWorker.generateId());
                param.setDocumentId(document.getId());
                param.setAlias(paramAddRequest.getAlias());
                param.setParam(paramAddRequest.getParam());
                param.setValue(paramAddRequest.getValue());
                param.setSorted(paramAddRequest.getSorted());
                documentMapper.insertParam(param);
            }
        }
        documentMapper.insert(document);
        return Result.ok();
    }
}
